package com.cskaoyan.market.service.impl;


import com.cskaoyan.market.bo.MarketGoodsBo;
import com.cskaoyan.market.vo.*;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.service.MarketGoodsService;
import com.cskaoyan.market.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MarketGoodsServiceImpl implements MarketGoodsService {


    public List<MarketCategory> getCategoryList(Integer pid) {
        SqlSession session = MyBatisUtil.getSession();
        MarketCategoryMapper mapper = session.getMapper(MarketCategoryMapper.class);
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        marketCategoryExample.or().andPidEqualTo(pid);
        List<MarketCategory> marketCategories = mapper.selectByExample(marketCategoryExample);
        session.commit();
        session.close();
        return marketCategories;
    }

    public List<CategoryUseInCABVo> packageMarketCategoryList(List<MarketCategory> CategoryList) {
        List<CategoryUseInCABVo> CategoryUseInCABVos = new ArrayList<>();
        for (MarketCategory marketCategory : CategoryList) {
            CategoryUseInCABVo CategoryUseInCABVo = new CategoryUseInCABVo(marketCategory);
            List<CategoryUseInCABVo> packagedCategorys = packageMarketCategoryList(getCategoryList(marketCategory.getId()));
            if (packagedCategorys.size() > 0) {
                CategoryUseInCABVo.setChildren(packagedCategorys);
            }
            CategoryUseInCABVos.add(CategoryUseInCABVo);
        }
        return CategoryUseInCABVos;
    }

    public List<BrandVo> getBrandsList() {
        SqlSession session = MyBatisUtil.getSession();
        MarketBrandMapper mapper = session.getMapper(MarketBrandMapper.class);
        MarketBrandExample marketBrandExample = new MarketBrandExample();
        marketBrandExample.or().andDeletedEqualTo(false);
        List<MarketBrand> marketBrands = mapper.selectByExampleSelective(marketBrandExample, MarketBrand.Column.id, MarketBrand.Column.name);
        ArrayList<BrandVo> brandVos = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            brandVos.add(new BrandVo(marketBrand));
        }
        session.commit();
        session.close();
        return brandVos;
    }

    @Override
    public int createMarketGoods(MarketGoods marketGoods) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        marketGoods.setDeleted(false);
        marketGoods.setId(Integer.parseInt(marketGoods.getGoodsSn()));
        marketGoods.setAddTime(LocalDateTime.now());
        marketGoods.setUpdateTime(LocalDateTime.now());
        int insert = mapper.insert(marketGoods);
        session.commit();
        session.close();
        return insert;
    }

    @Override
    public int createMarketGoodsSpecifications(List<MarketGoodsSpecification> marketGoodsSpecification) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsSpecificationMapper mapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        int insert = 0;
        for (MarketGoodsSpecification goodsSpecification : marketGoodsSpecification) {
            goodsSpecification.setDeleted(false);
            goodsSpecification.setAddTime(LocalDateTime.now());
            goodsSpecification.setUpdateTime(LocalDateTime.now());
            insert = mapper.insertSelective(goodsSpecification);
            insert++;
        }
        session.commit();
        session.close();
        return insert;
    }

    @Override
    public int createMarketGoodsProduct(List<MarketGoodsProduct> marketGoodsProduct) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsProductMapper mapper = session.getMapper(MarketGoodsProductMapper.class);
        int insert = 0;
        for (MarketGoodsProduct goodsProduct : marketGoodsProduct) {
            goodsProduct.setDeleted(false);
            goodsProduct.setUpdateTime(LocalDateTime.now());
            goodsProduct.setUpdateTime(LocalDateTime.now());
            insert = mapper.insert(goodsProduct);
            insert++;
        }
        session.commit();
        session.close();
        return insert;
    }

    @Override
    public int createMarketGoodsAttribute(List<MarketGoodsAttribute> marketGoodsAttribute) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsAttributeMapper mapper = session.getMapper(MarketGoodsAttributeMapper.class);
        int insert = 0;
        for (MarketGoodsAttribute goodsAttribute : marketGoodsAttribute) {
            goodsAttribute.setDeleted(false);
            goodsAttribute.setAddTime(LocalDateTime.now());
            goodsAttribute.setUpdateTime(LocalDateTime.now());
            insert = mapper.insert(goodsAttribute);
            insert++;
        }
        session.commit();
        session.close();
        return insert;
    }

    @Override
    public Map<String, Object> getCatAndBrand() {
        List<MarketCategory> categoryList = getCategoryList(0);
        List<CategoryUseInCABVo> CategoryUseInCABVos = packageMarketCategoryList(categoryList);
        Map<String, Object> retCatAndBrand = new HashMap<>();
        retCatAndBrand.put("categoryList", CategoryUseInCABVos);
        List<BrandVo> brandsList = getBrandsList();
        retCatAndBrand.put("brandList", brandsList);
        return retCatAndBrand;
    }

//    @Override
//    public List<MarketGoods> readGoodsList(String page, String limit, String sort, String order, String id, String name, String goodsSn) {
//        SqlSession session = MyBatisUtil.getSession();
//        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
//        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
//        marketGoodsExample.orderBy(sort + " " + order);
//        MarketGoodsExample.Criteria criteria = marketGoodsExample.or().andDeletedEqualTo(false);
//        if (name != null && !"".equals(name)) {
//            criteria.andNameLike("%" + name + "%");
//        }
//        if (id != null && !"".equals(id)) {
//            criteria.andIdEqualTo(Integer.parseInt(id));
//        }
//        if (goodsSn != null && !"".equals(goodsSn)) {
//            criteria.andGoodsSnEqualTo(goodsSn);
//        }
//        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
//        List<MarketGoods> marketGoods = mapper.selectByExample(marketGoodsExample);
//        session.commit();
//        session.close();
//        return marketGoods;
//    }

    /*
     * @author lanch
     * @since 2023/05/07 15:53
     */
    private ArrayList<Brand> brandList;
    private MarketCategoryExample categoryExample2;

    //获取商品列表
    @Override
    public List<MarketGoods> getGoods(Integer page, Integer limit, String sort, String order, String goodsSn, String name, String goodsId) {
        //page:页数，limit:一页含有数据量
        SqlSession sqlSession = MyBatisUtil.getSession();
        MarketGoodsMapper goodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.or();
        criteria.andDeletedEqualTo(false);
        //按照sort(add_time),desc排序
        marketGoodsExample.orderBy(sort + " " + order);
        //id和Sn不为空的话添加到example中
        if (!StringUtils.isEmpty(goodsSn)) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andIdEqualTo(Integer.parseInt(goodsId));
        }
        //名字使用模糊匹配
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        //分页
        PageHelper.startPage(page, limit);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(marketGoodsExample);
        sqlSession.commit();
        sqlSession.close();
        return goodsList;
    }

    //获取商品详细信息
    @Override
    public HashMap<String, Object> getGoodsDetail(Integer id) {
        /*
         * 获取goods：商品详情
         * 根据传入id去category获取categoryid
         * 获取attributes：参数
         * 获取specifications：规格信息
         * 获取products:库存
         * */
        // ArrayList<Integer> categoryIds = new ArrayList<>();
        Long[] categoryIds = new Long[2];
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        //获取目标商品
        MarketGoods targetGoods = goodsMapper.selectByPrimaryKey(id);
        //获取分类id
        Integer categoryId = targetGoods.getCategoryId();
        //获取目标商品分类
        MarketCategoryMapper marketCategoryMapper = session.getMapper(MarketCategoryMapper.class);
        MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(categoryId);
        //商品分类id放在数组第一位，父类id放在第二位；
        categoryIds[0] = (long) categoryId;
        categoryIds[1] = (long) marketCategory.getPid();
        //获取目标商品的attributes
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.or().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(marketGoodsAttributeExample);
        //获取目标商品的specifications
        MarketGoodsSpecificationMapper marketGoodsSpecificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.or().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> specifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        //获取目标商品的products
        MarketGoodsProductMapper goodsProductMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.or().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> products = goodsProductMapper.selectByExample(marketGoodsProductExample);

        HashMap<String, Object> result = new HashMap<>();
        result.put("categoryIds", categoryIds);
        result.put("goods", targetGoods);
        result.put("attributes", attributes);
        result.put("specifications", specifications);
        result.put("products", products);
        // MarketCategoryMapper categoryMapper = session.getMapper(MarketCategoryMapper.class);
        // new MarketCategoryExample().or().
        session.commit();
        session.close();
        return result;
    }

    //删除一件商品
    @Override
    public void deleteGoodsById(MarketGoods o, Integer id) {
        //todo:没有改变对象的delete值为true；
        o.setDeleted(true);
        o.setUpdateTime(LocalDateTime.now());
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        // goodsMapper.up
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.or().andIdEqualTo(o.getId());
        int i = goodsMapper.updateByExample(o, marketGoodsExample);
        session.commit();
        session.close();

    }

    //更新一件商品信息
    @Override
    public void updateGoods(MarketGoodsBo marketGoodsBo) {
        MarketGoods goods = marketGoodsBo.getGoods();
        List<MarketGoodsSpecification> specifications = marketGoodsBo.getSpecifications();
        List<MarketGoodsProduct> products = marketGoodsBo.getProducts();
        List<MarketGoodsAttribute> attributes = marketGoodsBo.getAttributes();
        SqlSession session = MyBatisUtil.getSession();
        //修改goods表
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        goods.setUpdateTime(LocalDateTime.now());
        goodsMapper.updateByPrimaryKey(goods);
        //修改specifications表
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);
        for (MarketGoodsSpecification specification : specifications) {
            specification.setUpdateTime(LocalDateTime.now());
            specificationMapper.updateByPrimaryKey(specification);
        }
        //    修改products表
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        for (MarketGoodsProduct product : products) {
            product.setUpdateTime(LocalDateTime.now());
            productMapper.updateByPrimaryKey(product);
        }
        //    修改attributes表
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setUpdateTime(LocalDateTime.now());
            attributeMapper.updateByPrimaryKey(attribute);
        }
        session.commit();
        session.close();


    }

    //获取商品的类目以及制造商
//    @Override
//    public MarketGoodsCatAndBrandVo getCatAndBrand() {
//        MarketGoodsCatAndBrandVo catAndBrandVo = new MarketGoodsCatAndBrandVo();
//        SqlSession session = MyBatisUtil.getSession();
//        MarketCategoryMapper categoryMapper = session.getMapper(MarketCategoryMapper.class);
//        MarketBrandMapper brandMapper = session.getMapper(MarketBrandMapper.class);
//        List<CategoryLvOne> categoryList = new ArrayList<>();
//        ArrayList<Brand> brandList = new ArrayList<>();
//        //先遍历一遍category表获取一级分类
//        MarketCategoryExample categoryExample = new MarketCategoryExample();
//        categoryExample.or().andLevelEqualTo("L1");
//        //获取到Lv为L1的category
//        List<MarketCategory> lv1CategoryList = categoryMapper.selectByExample(categoryExample);
//
//        for (MarketCategory marketCategory : lv1CategoryList) {
//            CategoryLvOne categoryLvOne = new CategoryLvOne(marketCategory.getId(), marketCategory.getName(), new ArrayList<CategoryLvTwo>());
//            categoryList.add(categoryLvOne);
//        }
//        //获取Lv2的category，放入对应的categoryLv1s里面的对象的childrenList
//        MarketCategoryExample categoryExample2 = new MarketCategoryExample();
//        categoryExample2.or().andLevelEqualTo("L2");
//        List<MarketCategory> Lv2CategoryList = categoryMapper.selectByExample(categoryExample2);
//        for (MarketCategory category : Lv2CategoryList) {
//            for (CategoryLvOne categoryLv1 : categoryList) {
//                if (category.getPid().equals(categoryLv1.getValue())) {
//                    CategoryLvTwo categoryLvTwo = new CategoryLvTwo(category.getId(), category.getName());
//                    List<CategoryLvTwo> children = categoryLv1.getChildren();
//                    children.add(categoryLvTwo);
//                    categoryLv1.setChildren(children);
//                }
//            }
//        }
//        //获取BrandList
//        MarketBrandExample marketBrandExample = new MarketBrandExample();
//        List<MarketBrand> brandList1 = brandMapper.selectByExample(marketBrandExample);
//        for (MarketBrand marketBrand : brandList1) {
//            Brand brand = new Brand(marketBrand.getId(), marketBrand.getName());
//            brandList.add(brand);
//        }
//        session.commit();
//        session.close();
//        MarketGoodsCatAndBrandVo marketGoodsCatAndBrandVo = new MarketGoodsCatAndBrandVo(categoryList, brandList);
//
//        return marketGoodsCatAndBrandVo;
//    }
}
